package org.credo.jms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class PubJMS {

	private static final String	DEFAULT_USERNAME		= "lion";
	private static final String	DEFAULT_PASSWORD		= "123456";
	private static final String	INITIAL_CONTEXT_FACTORY	= "org.jboss.naming.remote.client.InitialContextFactory";
	private static final String	PROVIDER_URL			= "remote://localhost:4447";

	public static void main(String[] args) throws NamingException, JMSException, IOException {
		final Properties env = new Properties();
		env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
		env.put(Context.PROVIDER_URL, PROVIDER_URL);
		env.put(Context.SECURITY_PRINCIPAL, DEFAULT_USERNAME);
		env.put(Context.SECURITY_CREDENTIALS, DEFAULT_PASSWORD);
		InitialContext context = new InitialContext(env);

		// 查找连接工厂(本地JNDI查找,没有必要凭证)
		ConnectionFactory cf = (ConnectionFactory) context.lookup("jms/RemoteConnectionFactory");
		javax.jms.Connection connection = cf.createConnection(DEFAULT_USERNAME, DEFAULT_PASSWORD);
		javax.jms.Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

		/**
		 * 在standalone-full.xml中找到 <subsystem
		 * xmlns="urn:jboss:domain:messaging:1.1"> 节点下找到<jms-destinations>节点，增加
		 * <jms-topic name="ServerNotificationTopic"> <entry
		 * name="topic/ServerNotification"/> <entry
		 * name="java:jboss/exported/jms/topic/ServerNotification"/>
		 * </jms-topic>
		 */
		// 4) "create" the queue/topic (using the topic name - not JNDI)
		// javax.jms.Topic topic =
		// session.createTopic("ServerNotificationTopic");
		//javax.jms.Topic topic = (javax.jms.Topic) context.lookup("jms/topic/ServerNotification");
		// 5) create producer
		// javax.jms.MessageProducer producer = session.createProducer(topic);
		Destination destination = (Destination) context.lookup("jms/topic/ServerNotification");
		MessageProducer producer = session.createProducer(destination);

		BufferedReader msgStream = new BufferedReader(new InputStreamReader(System.in));
		String line = null;
		boolean quitNow = false;
		do {
			System.out.print("输入信息: ");
			line = msgStream.readLine();
			if (line != null && line.trim().length() != 0) {
				TextMessage textMessage = session.createTextMessage();
				textMessage.setText(line);
				producer.send(textMessage);

				quitNow = line.equalsIgnoreCase("quit");
			}
		} while (!quitNow);

	}

}
